<template>
  <div class="container" id="container">
    <div id="canvas" class="canvas" ref="canvas">
      <div class="title">
           流水号为{{flowInfo.custSoNumber}}{{flowInfo.orderItemSeq != '' ? '(' + flowInfo.orderItemSeq +  ')' : '' }}的{{flowInfo.prodName}}{{flowInfo.serviceOfferName}}流程
      </div>
      <div class="returnBtn">
        <el-button type="primary" plain @click="zoom(0.1)">放大</el-button>
        <el-button type="primary" plain @click="zoom(-0.1)">缩小</el-button>
        <el-button type="primary" plain @click="upload">刷新</el-button>
        <!-- <el-button type="primary" plain @click="returnPage">返回</el-button> -->
      </div>
      <div>
        待处理：<i class="iconfont icon-daichuli"></i> 已处理：<i
          class="iconfont icon-yichuli"
        ></i>
        已终止：<i class="iconfont icon-zhongzhi"></i> 自动：<i
          class="iconfont icon-xunhuan"
        ></i>
        超时：<i class="iconfont icon-shijian"></i>
      </div>
    </div>
  </div>
</template>
<script>
import Modeler from "bpmn-js/lib/Viewer";
// import ModelingModule from "bpmn-js/lib/features/modeling";
import MoveCanvasModule from "diagram-js/lib/navigation/movecanvas";
// import zoomScroll from "@/components/custorder/flow-chart/zoomScroll.js";
import BPMService from "@/api/order/BPMService";
export default {
  data() {
    return {
      bpmnModeler: null, //创建的canvas对象
      processInstanceId: null,
      overlays: null,
      elementRegistry: null,
      scale: 0.7,
      exclusiveNodeTypes: [
        "bpmn:ExclusiveGateway",
        "bpmn:InclusiveGateway",
        "bpmn:Process",
        "bpmn:EndEvent",
        "bpmn:StartEvent",
        "bpmn:ParallelGateway",
      ],
      hisUserTaskIds: [],
      getInfo: [],
      flowInfo:{},//页面所需的数据
    };
  },

  components: {},
  created() {
    this.flowInfo = JSON.parse(sessionStorage.getItem("flowInfo"));
    this.processInstanceId = this.flowInfo.processInstanceId;
  },

  computed: {},

  mounted() {
    const canvas = this.$refs.canvas;
    this.bpmnModeler = new Modeler({
      container: canvas,
      additionalModules: [
        // ModelingModule, // 基础工具 MoveModule、SetColor 等依赖于此
        MoveCanvasModule, // 移动整个画布
        // zoomScroll, // 放大缩小
      ],
    });
    // this.queryProcessDefinitionXml(this.processInstanceId);
    this.getProcessId(this.processInstanceId)
    this.overlays = this.bpmnModeler.get("overlays");
    this.elementRegistry = this.bpmnModeler.get("elementRegistry");
  },

  methods: {
    async getProcessId(processInstanceId) {
      let result = await BPMService.activityInstance({
        processInstanceId: processInstanceId,
      });
      this.queryProcessDefinitionXml(result[0].processDefinitionId);
    },
    async queryProcessDefinitionXml(val) {
      let result = await BPMService.getBpmXml({
        processDefinitionId: val,
        // processDefinitionId:'bpm_011:13:b25803db-b965-11eb-a26b-00ff0edc792f',
      });
      this.bpmnModeler.importXML(result, (err) => {
        if (err) {
          // console.error(err)
        } else {
          // 这里是成功之后的回调, 可以在这里做一系列事情
          this.bpmnModeler.get("canvas").zoom("fit-viewport");
          this.markactivity();
        }
      });
      var canvasHeight = document.getElementById("canvas").offsetHeight;
      document.getElementById("container").style.height = canvasHeight + "px";
    },
    async markactivity() {
      let canvas = this.bpmnModeler.get("canvas");
      let result = await BPMService.activityInstance({
        processInstanceId: this.processInstanceId,
      });
      this.getInfo = result;
      result.forEach((item) => {
        const activityId = item.activityId;
        // const endTime = item.endTime;
        const type = item.activityType;
        this.hisUserTaskIds.push(activityId);
        let flag = false;
        for (let i = 0; i < result.length; i++) {
          result[i].endTime;
          if (result[i].activityId == activityId) {
            if (
              result[i].endTime == null ||
              result[i].endTime == undefined ||
              result[i].endTime == ""
            ) {
              flag = true;
              break;
            }
          }
        }
        if (!flag) {
          if (type == "exclusiveGateway") {
            // 如果是互斥网关则换样式
            canvas.addMarker(activityId.split("#")[0], "exclusiveGateway");
          } else if (type == "userTask") {
            //userTask类型，根据不通业务添加右下角添加图例
            this.addNodeIcon(
              activityId.split("#")[0],
              "icon-yichuli",
              "custom_icon_user_white"
            );
          }
          canvas.addMarker(activityId.split("#")[0], "highlight");
          const element = this.elementRegistry.find(
            (el) => el.id === activityId.split("#")[0]
          );
          element.outgoing.forEach((line) => {
            canvas.addMarker(line.id, "highlight");
          });
        }else {
          //当前活动节点
          canvas.addMarker(activityId.split("#")[0], "highlight-todo"); //高亮显示流程节点
          if (type == "userTask") {
            //流程节点右下角增加待等待图标
            this.addNodeIcon(
              activityId.split("#")[0],
              "icon-daichuli",
              "custom_icon_user_white"
            );
          }
        }
      });
      //添加点击事件
      this.addClick();
      //改变结束节点样式
      this.handleEndEventNode();
      //改变用户任务节点样式
      this.handleUserTaskNode();
    },
    addClick() {
      this.bpmnModeler.on("element.click", (e) => {
        let element = e.element;
        const nodeObj = document.getElementById("tnote");
        if (nodeObj) nodeObj.remove();
        //特殊节点不显示注释信息
        if (this.exclusiveNodeTypes.indexOf(element.type) != -1) return;
        this.clickInfo(element);
        // this.overlays.add(element.id, "note", {
        //   position: {
        //     bottom: 0,
        //     right: 0,
        //   },
        //   html: '<div class="lct" id="tnote"> <div class="lct-head"> <dl> <dt>业务接单（TACHE20490001）（136984--1420476）</dt> <dd>注意：该任务有2名参与者</dd> </dl> </div> <div class="lct-body"> <dl class="clearfix pb30"> <dt>1</dt> <dd> <p>工作项ID：686106</p> <p>参与者：北京电信公司</p> <p>任务状态：<span class="cOrg">待处理</span></p> <p>派发时间：2021-04-22  19:54:47</p> <p>完成时间：<span class="cRed">未完成</span></p> <p>完成时限：2021-04-26</p> <p>是否超时：<span class="cRed">是</span></p> </dd> </dl> <dl class="clearfix nob"> <dt>2</dt> <dd> <p>工作项ID：686106</p> <p>参与者：集团公司公司</p> <p>任务状态：<span class="cOrg">待处理</span></p> <p>派发时间：2021-04-22  19:54:47</p> <p>完成时间：<span class="cGreen">已完成</span></p> <p>完成时限：2021-04-26</p> <p>是否超时：否</p> </dd> </dl> </div> </div>',
        // });
      });
    },
    //获取点击事件内容
    async clickInfo(element) {
      let activityName = "";
      this.getInfo.forEach((item) => {
        if (element.id == item.activityId) {
          activityName = item.activityName;
        }
      });
      if (activityName == "") {
        return;
      }
      let parmas = {
        processInstanceId: this.processInstanceId,
        activityName: activityName,
        activityId: element.id,
      };
      const result = await BPMService.getBpmInfo(parmas);
      // const nodeObj = document.getElementById("tnote");
      // if (nodeObj) nodeObj.remove();
      let handleHtml = `<div class="lct" id="tnote"> <div class="lct-head"> <dl> <dt>${result.headerInfo}</dt> <dd>注意：该任务有${result.listInfo.length}名参与者</dd> </dl> </div>`;
      result.listInfo.forEach((item, index) => {
        if (index == result.listInfo.length - 1) {
          handleHtml += `<div class="lct-body">
              <dl class="clearfix nob">
                <dt>${index + 1}</dt>
                <dd>
                  <p style="margin-bottom:5px">${item.participants}</p>`;
        } else {
          handleHtml += `<div class="lct-body">
              <dl class="clearfix pb30">
                <dt>${index + 1}</dt>
                <dd>
                  <p style="margin-bottom:5px">${item.participants}</p>`;
        }
        if (item.State == "完成") {
          handleHtml += ` <p style="margin-bottom:5px">任务状态：<span class="cOrg">${item.State}</span></p> `;
        } else {
          handleHtml += ` <p style="margin-bottom:5px">任务状态：<span class="cRed">${item.State}</span></p> `;
        }
        if (item.participantOrg != "") {
          handleHtml += ` <p style="margin-bottom:5px">所属组织：${item.participantOrg}</p>`;
        }
        handleHtml += `
                <p style="margin-bottom:5px">派发时间：${item.startTime}</p>
                <p style="margin-bottom:5px">完成时间：${item.endTime}</p>
                <p style="margin-bottom:5px">完成时限：${item.limit}</p>
                <p style="margin-bottom:5px">预警日期：${item.warningDate}</p> `;
        if (item.isTimeOut == "是") {
          handleHtml += `<p style="margin-bottom:5px">是否超时：<span class="cRed">${item.isTimeOut}</span></p></dd> </dl> </div> `;
        } else {
          handleHtml += `<p style="margin-bottom:5px">是否超时：${item.isTimeOut}</p> </dd> </dl> </div> `;
        }
      });
      this.overlays.add(element.id, "note", {
        position: {
          bottom: 0,
          right: 0,
        },
        html: handleHtml,
      });
    },
    /**
     * 处理结束节点的样式，自定义样式类endEvent，可根据具体情况自己定义样式
     */
    handleEndEventNode() {
      const endEventList = this.elementRegistry.filter(
        (item) => item.type === "bpmn:EndEvent"
      );
      if (endEventList) {
        let canvas = this.bpmnModeler.get("canvas");
        endEventList.forEach((end) => {
          canvas.addMarker(end.id, "endEvent");
        });
      }
    },
    /**
     * 处理用户任务节点的特殊处理：增加角标
     * 根据业务场景使用
     */
    handleUserTaskNode() {
      const userTaskList = this.elementRegistry.filter(
        (item) => item.type === "bpmn:UserTask"
      );
      if (userTaskList) {
        userTaskList.forEach((task) => {
          if (this.hisUserTaskIds.indexOf(task.id) == -1) {
            // this.addNodeIcon(task.id, "icon-shijian", "custom_icon_user_red");
          }
        });
      }
    },
    /**
     * 放大/缩小流程图
     * @param val
     */
    zoom(val) {
      let newScale = !val
        ? 1.0
        : this.scale + val <= 0.1
        ? 0.1
        : this.scale + val;
      this.bpmnModeler.get("canvas").zoom(newScale);
      this.scale = newScale;
    },
    upload(){
      window.location.href = "orders.html?router=flowChart"
    },
    /**
     * 右下角增加自定义的图标（使用icon方式）
     * @param id :element id
     * @param name :图标类型名称
     * @param cls :图标的自定义样式
     */
    addNodeIcon(id, name, cls) {
      this.overlays.add(id, "icon", {
        position: {
          bottom: 30,
          right: 25,
        },
        html:
          '<div class="' +
          cls +
          '" ><i class="iconfont ' +
          name +
          '"></i></div>',
      });
    },
    // beforeunloadHandler(){
    //   e = e || window.event;
    //   if (e) {
    //     e.returnValue = "您是否确认离开此页面-您输入的数据可能不会被保存";
    //   }
    //   return "您是否确认离开此页面-您输入的数据可能不会被保存";
    // },
    // //页面刷新事件
    // onloadPage(){
    //    window.location.href = "orders.html?router=flowChart"
    // }
    // returnPage() {
    //   this.$router.push({
    //     path: "/custorder",
    //   });
    // },
  },
};
</script>
<style lang='scss' scoped>
.container {
  width: 100%;
  height: 100%;
}
.title {
  position: fixed;
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  top: 0;
  left: 0;
  text-align: center;
  background-color: #a8c5d6;
  z-index: 9999;
}
.returnBtn {
  width: 100%;
  text-align: right;
  padding: 45px 30px 0 0;
}
.canvas {
  width: 100%;
  height: 200%;
  background-color: #ffffff;
}
.iconfont {
  margin-right: 15px;
}
</style>
